package com.zcxk.constant;

import io.vertx.core.json.JsonObject;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * @author kk
 * @date 2024-11-4 11:36
 */
public class Constants {
  public static final String DCP_INTERFACE_ACTIVE_DEVICES = "/activeDevices";

  public static final String DCP_INTERFACE_HISTORY_HR = "/history/hr";

  public static final String DCP_INTERFACE_HISTORY_SPO2 = "/history/spo2";

  public static final String DCP_INTERFACE_HISTORY_RESP = "/history/resp";

  public static final String DCP_INTERFACE_HISTORY_NIBP = "/history/nibp";

  public static final String DCP_INTERFACE_HISTORY_TEMP = "/history/temp";

  private static final JsonObject constants;

  // 用于存储动态设置的 SERVER_HOST
  private static String ServerHost;

  static {
    // 使用类加载器读取 JSON 配置文件
    InputStream inputStream = Constants.class.getClassLoader().getResourceAsStream("config.json");
    if (inputStream == null) {
      throw new RuntimeException("Constants file not found");
    }

    // 读取输入流并转为字符串
    String jsonString;
    try {
      jsonString = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    } catch (Exception e) {
      throw new RuntimeException("Failed to read constants file", e);
    }

    // 解析 JSON 字符串
    JsonObject config = new JsonObject(jsonString);
    constants = config.getJsonObject("Constants");

    try {
      setServerHost();
    } catch (UnknownHostException e) {
      throw new RuntimeException(e);
    }
  }

  public static String getSecretKey() {
    return constants.getString("SECRET_KEY");
  }

  public static String getServerHost() {
    return ServerHost != null ? ServerHost : constants.getString("SERVER_HOST");
  }

  public static int getWebServerPort() {
    return constants.getInteger("WEB_SERVER_PORT");
  }

  public static int getDcpApiServerPort() {
    return constants.getInteger("DCP_API_SERVER_PORT");
  }

  public static int getWsServerPort() {
    return constants.getInteger("WS_SERVER_PORT");
  }

  public static int getDcpWsServerPort() {
    return constants.getInteger("DCP_WS_SERVER_PORT");
  }

  public static int getMaxHTTPPoolSize() {
    return constants.getInteger("MAX_HTTP_POOL_SIZE");
  }

  public static int getMaxReconnectRetries() {
    return constants.getInteger("MAX_RECONNECT_RETRIES");
  }

  private static void setServerHost() throws UnknownHostException {
    InetAddress localHost = InetAddress.getLocalHost();
    ServerHost = localHost.getHostAddress();
  }
}
